<?php

namespace app\api\controller;

use app\admin\model\share\ShareUser;
use app\common\controller\Api;
use app\admin\model\shopro\user\User;
use app\common\model\User as FUser;
use think\exception\PDOException;
use think\Db;
use addons\shopro\model\UserWalletApply as WithDraw;
use app\admin\model\shopro\order\OrderExpress;
use linghuo\v2\Linghuo;
use addons\shopro\model\Order;
//use app\common\model\User;

/**
 * 手机端showdata tian add
 */
class Showdata extends Api
{

    
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test','order_update','withdraw_list','withdraw_update', 'share_user_type_update'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->orderModel = new \app\admin\model\shopro\order\Order;
        $this->storeModel = new \app\admin\model\shopro\store\Store;
        $this->applyModel = new \app\admin\model\UserWithdraw;
        $this->model = new \app\admin\model\share\ShareUser;
        $this->modelMoney = new \app\admin\model\share\Money;
        $this->modelReward = new \app\admin\model\share\Reward;

    }

    public function get_user_list()
    {
        $offset = $this->request->post("offset"); // 第几页
        $offset = empty( $offset) ? 0 :  bcsub($offset,1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $sort = $this->request->post("sort",'id');
        $limit = empty($limit) ? 10 :  $limit;
        $page = empty($offset) ? 0 : bcmul($offset,$limit);
        $user = $this->auth->getUser();        //$this->auth->id
        $username = $this->request->post("username");
        $nickname = $this->request->post("nickname");
        $mobile = $this->request->post("mobile");
        $role = $this->request->post("role");
        $role_url = $this->request->post("role_url");//团队筛选  网体路径
        $inviter_mobile = $this->request->post("inviter_mobile");//邀请人手机号
        $parent_mobile = $this->request->post("parent_mobile");//直接负责人手机号
        $is_sep_income = $this->request->post("is_sep_income");//分割标识  是否分隔收益 0否 1是
        $is_union = $this->request->post("is_union");//联创伙伴  是否联创伙伴 0否 1是
        $share_user =ShareUser::where("user_id",$user['id'])->find();
        $type=$this->request->post("type");//1 项目负责人   2独立负责人

        if(empty($type)){
            $this->error("type必填");
        }
//        项目负责人 share_use  里面is_leader = 1 独立节点负责人 is_sep_income = 1
//        会员信息
//        项目负责人 所有后台的数据
//        独立负责人 根据role_url查询

//        if($share_user["is_leader"]==1){//项目负责人 所有后台的数据
//            $where_agent="1=1";
//        }else{
//            if($share_user["is_sep_income"]==1){//独立负责人 根据role_url查询
//                $where_agent = "role_url like '%" . $user['id'] . "%'";
//            }else{
//                $this->error("您无权查看该信息");
//            }
//        }

        if($type==1){
            $where_agent="1=1";
        }elseif($type==2){
            if($share_user["is_sep_income"]==1){//独立负责人 根据role_url查询
                $where_agent = "role_url like '%" . $user['id'] . "%'";
            }else{
                $this->error("您无权查看该信息");
            }
        }

        if (!empty($role_url)) {
            $where_agent = $where_agent . " and share_user.role_url like '%" .$role_url. "%'";
        }
        if (!empty($username)) {
            $where_agent = $where_agent . " and user.username like '%" . $username . "%'";
        }
        if (!empty($nickname)) {
            $where_agent = $where_agent . " and user.nickname like '%" . $nickname . "%'";
        }
        if (!empty($mobile)) {
            $where_agent = $where_agent . " and user.mobile like '%" . $mobile . "%'";
        }
        if (!empty($role)) {
            $where_agent = $where_agent . " and share_user.role =".$role ;
        }
        if (!empty($inviter_mobile)) {
            $where_agent = $where_agent . " and u_inviter.mobile like '%".$inviter_mobile. "%'";
        }
        if (!empty($parent_mobile)) {
            $where_agent = $where_agent . " and u_parent.mobile like '%".$parent_mobile."%'" ;
        }
        if (!empty($is_sep_income)) {
            $where_agent = $where_agent . " and is_sep_income =".$is_sep_income ;
        }
        if (!empty($is_union)) {
            $where_agent = $where_agent . " and is_union =".$is_union ;
        }
        $order="desc";
        $list = ShareUser::alias('share_user')
            ->with('user')
            ->join('share_user_flags f', 'f.user_id = share_user.user_id', 'LEFT')
            ->join('user u_inviter', 'u_inviter.id = share_user.inviter_id', 'LEFT')
            ->join('user u_parent', 'u_parent.id = share_user.parent_id', 'LEFT')
            ->where($where_agent)
            ->field('share_user.*,share_user.user_flags as u_user_flags,f.user_flags,user.username,user.mobile,u_inviter.mobile as inviter_mobile,u_parent.mobile as parent_mobile')
            ->order($sort, $order)
            ->limit($page,$limit)
            //->fetchSql()->select();
            ->select();
        //var_dump($list);die;
//        "total" => $list->total(), "rows" => $list->items()
        $this->success('成功', $list);
    }

    //用户信息详情
    public function user_detail(){
        $user_id = $this->request->post("user_id");
        if(empty($user_id)){
            $this->error("用户id参数必填");
        }
        $row = $this->model->get(['user_id' => $user_id]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $user = FUser::get($row['user_id']);

        $share_user = Db::name("share_user")->where(['user_id' => $row['user_id']])->find();
        $parent_user = Db::name("share_user")->where(['user_id' => $row['parent_id']])->find();
        $flags = Db::name("share_user_flags")->where(['user_id' => $row['user_id']])->find();

        $user_parent = FUser::get($row['parent_id']);
        $row->nickname = empty($user) ? '无' : $user['nickname'];
        $row->mobile = empty($user) ? '无' : $user['mobile'];
        $row->parent_mobile = empty($user_parent) ? '无' : $user_parent['mobile'];
        $row->parent_nickname = empty($user_parent) ? '无' : $user_parent['nickname'];
        $row->parent_role = empty($parent_user) ? '无' : $parent_user['role'];
        $row->is_sep_income = empty($share_user) ? '无' : $share_user['is_sep_income'];
        $row->user_flags = empty($flags) ? '无' : $flags['user_flags'];

        $invite_user = Db::name("user")->where(['id' => $row['inviter_id']])->find();
        $row->inviter_mobile = empty($invite_user) ? '无' : $invite_user['mobile'];



        $data_=$row->toArray();
        $data_["user"]= Db::name("user")->where(['id' => $row['user_id']])->find();
        //数据统计开始
        $user_id = $row['user_id'];
        $all_nums = $this->model
            ->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])
            ->whereOr("user_id", $row['user_id'])
            ->count();//总人数
        //->fetchSql()->select();
        //var_dump($all_nums);die;
        $all_score = $this->model->with('user')
            ->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])
            ->whereOr("user_id", $row['user_id'])
            ->sum("share_user.score");//总积分
        $all_price = $this->model->with('user')->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])->whereOr("user_id", $row['user_id'])->sum("share_user.price");//总余额
        $all_jin = $this->model->with('user')
            ->where(['role_url' => ['like', "%" . '/' . $row['user_id'] . $row['role_url'] . "%"]])
            ->where("share_user.role", 6)
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->count();//金牌人数
        $all_yin = $this->model->with('user')
            ->where("share_user.role", 5)
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->count();//银牌人数
        $all_xing1 = $this->model->with('user')
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 3)
            ->count();//一星网点
        $all_xing2 = $this->model->with('user')
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 4)
            ->count();//二星网点
        $all_daiyan = $this->model->with('user')
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 2)
            ->count();//代言人
        $all_tuiguang = $this->model->with('user')
            ->where(function ($query) use ($user_id, $row) {
                $query->whereOr(['role_url' => ['like', "%" . '/' . $user_id . $row['role_url'] . "%"]])
                    ->whereOr("user_id", $user_id);
            })
            ->where("share_user.role", 1)
            ->count();//推广员
        $data_["all_nums"] = $all_nums;//总人数
        $data_["all_score"] = $all_score;//总积分
        $data_["all_price"] = $all_price;//总余额
        $data_["all_jin"] = $all_jin;//金牌人数
        $data_["all_yin"] = $all_yin;//银牌人数
        $data_["all_xing1"] = $all_xing1;//一星网点
        $data_["all_xing2"] = $all_xing2;//二星网点
        $data_["all_daiyan"] = $all_daiyan;//代言人
        $data_["all_tuiguang"] = $all_tuiguang;//推广员
        //数据统计结束
        $this->success('成功', $data_);
    }

    //重置密码
    public function reset_pwd(){
        $user_id = $this->request->post("user_id");
        if(empty($user_id)){
            $this->error("用户id参数必填");
        }
        $row = $this->model->get(['user_id' => $user_id]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $user = FUser::get($row['user_id']);
        $salt = \fast\Random::alnum();
        $user->password = \app\common\library\Auth::instance()->getEncryptPassword('123456', $salt);
        $user->salt = $salt;
        $res = $user->save();
        if ($res) {
            $this->error(__("密码重置成功"));
        } else {
            $this->error(__("密码重置失败"));
        }
    }

    /**
     * 禁用
     */
    public function disable($ids = null)
    {
        $user_id = $this->request->post("user_id");
        if(empty($user_id)){
            $this->error("用户id参数必填");
        }
        $row = $this->model->get(['user_id' => $user_id]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Db::startTrans();
        $share_status = Db::name("share_user")->where(['id' => $ids])->update(['role' => 0]);
        $u_status = Db::name("user")->where(['id' => $row['user_id']])->update(['status' => 'forbidden']);
        if ($share_status !== false && $u_status) {
            Db::commit();
            $this->success("禁用成功");
        } else {
            Db::rollback();
            $this->error(__($share_status . "禁用失败" . $u_status));
        }

    }
    //删除实名
    public function userdel($ids = null)
    {

        $user_id = $this->request->post("user_id");
        if(empty($user_id)){
            $this->error("用户id参数必填");
        }
        $row = $this->model->get(['user_id' => $user_id]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $da = Db::name("user_id_card")->where(['user_id' => $row['user_id']])->find();
        if (!$da) {
            $this->error("此用户没有实名，不用删除");
        }
        $res = Db::name("user_id_card")->where(['user_id' => $row['user_id']])->delete();
        if ($res) {
            $this->error(__("删除成功"));
        } else {
            $this->error(__("删除失败"));
        }
    }

    //零批收益 广告收益
    public function ling_adv_list(){
        $offset = $this->request->post("offset"); // 第几页
        $offset = empty( $offset) ? 0 :  bcsub($offset,1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $sort = $this->request->post("sort",'id');
        $limit = empty($limit) ? 10 :  $limit;
        $page = empty($offset) ? 0 : bcmul($offset,$limit);
        $user = $this->auth->getUser();        //$this->auth->id
        $order_id = $this->request->post("order_id");//订单id
        $mobile = $this->request->post("mobile");
        $role = $this->request->post("role");//级别
        $type = $this->request->post("type");//类型

        $where_agent = "1=1";

//        项目负责人 share_use  里面is_leader = 1 独立节点负责人 is_sep_income = 1
//        零批收益
//        项目负责人 所有后台的数据
//        独立负责人 无权限
        $share_user =ShareUser::where("user_id",$user['id'])->find();
        if($share_user["is_leader"]==1){//项目负责人 所有后台的数据
            $where_agent="1=1";
        }else{
            $this->error("您无权查看该信息");
            if($share_user["is_sep_income"]==1){//独立负责人 无权限
                $this->error("您无权查看该信息");
            }
        }
        if (!empty($order_id)) {
            $where_agent = $where_agent . " and money.order_id =".$order_id;
        }
        if (!empty($mobile)) {
            $where_agent = $where_agent . " and user.mobile like '%" . $mobile . "%'";
        }
        if (!empty($role)) {
            $where_agent = $where_agent . " and money.role =".$role ;
        }
        if (!empty($type)) {
            $where_agent = $where_agent . " and money.type =".$type ;
        }
        $order="desc";

//        $have_flags_ = Db::name("share_user_flags")
//            ->where("user_id",$user['id'])
//            ->find();
//        if(empty($have_flags_)){//直接查对应订单表中 flags为空的数据
//            $list = $this->modelMoney->alias('money')
//                ->with('user')
//                ->join('share_user', 'share_user.user_id = money.user_id', 'LEFT')
//                ->join('shopro_order o', 'o.id = money.order_id', 'LEFT')
//                ->where("money.user_flags",'=','')
//                ->where($where_agent)
//                ->field('money.*,user.username,user.mobile,o.order_sn')
//                ->order($sort, $order)
//                ->limit($page,$limit)
//                ->select();
//        }else{
//            $where_agent = $where_agent . " and money.user_flags ='".$have_flags_["user_flags"]."'" ;
//            $list = $this->modelMoney->alias('money')
//                ->with('user')
//                ->join('share_user', 'share_user.user_id = money.user_id', 'LEFT')
//                ->join('shopro_order o', 'o.id = money.order_id', 'LEFT')
//                ->where($where_agent)
//                ->field('money.*,user.username,user.mobile,o.order_sn')
//                ->order($sort, $order)
//                ->limit($page,$limit)
//                //->fetchSql()->select();
//                ->select();
//            //var_dump($list);die;
//            ///var_dump(6666);
//        }


        //$where_agent = $where_agent . " and money.user_flags ='".$have_flags_["user_flags"]."'" ;
        $list = $this->modelMoney->alias('money')
            ->with('user')
            ->join('share_user', 'share_user.user_id = money.user_id', 'LEFT')
            ->join('shopro_order o', 'o.id = money.order_id', 'LEFT')
            ->where($where_agent)
            ->field('money.*,user.username,user.mobile,o.order_sn')
            ->order($sort, $order)
            ->limit($page,$limit)
            //->fetchSql()->select();
            ->select();
        //var_dump($list);die;
        ///var_dump(6666);
        //var_dump($list);die;
//        "total" => $list->total(), "rows" => $list->items()
        $this->success('成功', $list);

    }
    //零批收益 广告收益详情
    public function ling_adv_detail(){
        $id = $this->request->post("id");
        if(empty($id)){
            $this->error("id参数必填");
        }
        $row = $this->modelMoney->get(['id' => $id]);
        $shop_order=Order::find($row["order_id"]);
        if(empty($shop_order)){
            $row["order_sn"]="";
        }else{
            $row["order_sn"]=$shop_order["order_sn"];
        }

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row["user"] = FUser::get($row['user_id']);
//        $share_user = Db::name("share_user")->where(['user_id' => $row['user_id']])->find();
//        $flags = Db::name("share_user_flags")->where(['user_id' => $row['user_id']])->find();
//        $row->nickname = empty($user) ? '无' : $user['nickname'];
//        $row->mobile = empty($user) ? '无' : $user['mobile'];
//        $row->is_sep_income = empty($share_user) ? '无' : $share_user['is_sep_income'];
//        $row->user_flags = empty($flags) ? '无' : $flags['user_flags'];
        $data_=$row;
        //数据统计结束
        $this->success('成功', $data_);
    }

    //广告创收
    public function adv_cs_list(){
        $offset = $this->request->post("offset"); // 第几页
        $offset = empty( $offset) ? 0 :  bcsub($offset,1);
        $limit = $this->request->post("limit"); // 一页显示几行
        $sort = $this->request->post("sort",'id');
        $limit = empty($limit) ? 10 :  $limit;
        $page = empty($offset) ? 0 : bcmul($offset,$limit);
        $user = $this->auth->getUser();        //$this->auth->id
        $order_id = $this->request->post("order_id");//订单id
        $mobile = $this->request->post("mobile");
        $role = $this->request->post("role");//级别
        $type = $this->request->post("type");//类型
        $user_flags = $this->request->post("user_flags");//分割标识


        $where_agent = "1=1";


//        项目负责人 share_use  里面is_leader = 1 独立节点负责人 is_sep_income = 1
//        广告创收
//        项目负责人 所有后台的数据
//        独立负责人 无权限
        $share_user =ShareUser::where("user_id",$user['id'])->find();
        if($share_user["is_leader"]==1){//项目负责人 所有后台的数据
            $where_agent="1=1";
        }else{
            $this->error("您无权查看该信息");
            if($share_user["is_sep_income"]==1){//独立负责人 无权限
                $this->error("您无权查看该信息");
            }
        }
        if (!empty($order_id)) {
            $where_agent = $where_agent . " and reward.order_id =".$order_id;
        }
        if (!empty($mobile)) {
            $where_agent = $where_agent . " and user.mobile like '%" . $mobile . "%'";
        }
        if (!empty($user_flags)) {
            $where_agent = $where_agent . " and reward.user_flags like '%" . $user_flags . "%'";
        }
        if (!empty($role)) {
            $where_agent = $where_agent . " and share_user.role =".$role ;
        }
        if (!empty($type)) {
            $where_agent = $where_agent . " and reward.type =".$type ;
        }
        $order="desc";


//        $have_flags_ = Db::name("share_user_flags")
//            ->where("user_id",$user['id'])
//            ->find();
//        if(empty($have_flags_)){//直接查对应订单表中 flags为空的数据
//            $list =$this->modelReward->alias('reward')
//                ->with('user')
//                ->join('share_user', 'share_user.user_id = reward.user_id', 'LEFT')
//                ->where("reward.user_flags",'=','')
//                ->where($where_agent)
//                ->field('reward.*,user.username,user.mobile')
//                ->order($sort, $order)
//                ->limit($page,$limit)
//                ->select();
//        }else{
//            $where_agent = $where_agent . " and reward.user_flags ='".$have_flags_["user_flags"]."'" ;
//            $list = $this->modelReward->alias('reward')
//                ->with('user')
//                ->join('share_user', 'share_user.user_id = reward.user_id', 'LEFT')
//                ->where($where_agent)
//                ->field('reward.*,user.username,user.mobile')
//                ->order($sort, $order)
//                ->limit($page,$limit)
//                //->fetchSql()->select();
//                ->select();
//            //var_dump($list);die;
//            ///var_dump(6666);
//        }

        $list = $this->modelReward->alias('reward')
            ->with('user')
            ->join('share_user', 'share_user.user_id = reward.user_id', 'LEFT')
            ->where($where_agent)
            ->field('reward.*,user.username,user.mobile')
            ->order($sort, $order)
            ->limit($page,$limit)
            //->fetchSql()->select();
            ->select();
        //var_dump($list);die;
        ///var_dump(6666);
        //var_dump($list);die;
//        "total" => $list->total(), "rows" => $list->items()
        $this->success('成功', $list);

    }
    //广告创收 详情
    public function adv_cs_detail(){
        $id = $this->request->post("id");
        if(empty($id)){
            $this->error("id参数必填");
        }
        $row = $this->modelReward->get(['id' => $id]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
//        $user = FUser::get($row['user_id']);
//        $share_user = Db::name("share_user")->where(['user_id' => $row['user_id']])->find();
//        $flags = Db::name("share_user_flags")->where(['user_id' => $row['user_id']])->find();
//        $row->nickname = empty($user) ? '无' : $user['nickname'];
//        $row->mobile = empty($user) ? '无' : $user['mobile'];
//        $row->is_sep_income = empty($share_user) ? '无' : $share_user['is_sep_income'];
//        $row->user_flags = empty($flags) ? '无' : $flags['user_flags'];
        $data_=$row;
        //数据统计结束
        $this->success('成功', $data_);
    }

}
